package com.huyun.web.concurrency.countdownDemo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @author huyunqiang
 * @date 2020/1/8 16:38
 *  减小计数（CountDown）
 *  主线程调用 #await() 方法告诉 CountDownLatch 阻塞等待指定数量的计数被减少，然后其它线程调用 CountDownLatch 的 #countDown() 方法，减小计数(不会阻塞)。
 *  等待计数被减少到零，主线程结束阻塞等待，继续往下执行。
 */
public class CountDownDeom {
    final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch=new CountDownLatch(2);//两个工人的协作
        Worker worker1=new Worker("zhang san", 5000, latch);
        Worker worker2=new Worker("li si", 8000, latch);
        worker1.start();//
        worker2.start();//
        latch.await();//等待所有工人完成工作
        System.out.println("两个人一起执行工作---all work done at "+sdf.format(new Date()));
    }


    static class Worker extends Thread{
        String workerName;
        int workTime;
        CountDownLatch latch;
        public Worker(String workerName ,int workTime ,CountDownLatch latch){
            this.workerName=workerName;
            this.workTime=workTime;
            this.latch=latch;
        }
        @Override
        public void run(){
            System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
            doWork(workerName);//工作了
            System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
            latch.countDown();//工人完成工作，计数器减一
        }

        private void doWork(String name){
            try {
                System.out.println(name+"开始处理业务逻辑开始工作");
                //Thread.sleep(workTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
